# -*- coding: utf-8 -*-
import twython
from google.appengine.ext import db
from datetime import datetime
from setting import Setting
from models.searchlist import SearchList
import logging
import re
import random

class GetSearchList():
    twitter = twython.setup(authtype="Basic",
                            username=Setting.userName,
                            password=Setting.password)
    #mentions = twitter.getUserMentions(count="10")


    slist = twitter.searchTwitter(u"ねんがんの OR 念願の")
    for result in slist['results']:
        # 必要な情報取得
        insIt = False
        text = result["text"]
        from_user = result["from_user"]
        
        # 取得内容確認
        #logging.info(result["text"])
        #logging.info(result["from_user"])
        #continue

        if re.search("RT", text):
            insIt = False
        elif re.search("^@" + Setting.userName, text):
            insIt = False
        else:
            SearchStore = SearchList.gql("WHERE post_id = :1", str(result["id"]))
            if not SearchStore.get():
                insIt = True
        
        #logging.info("id:" + str(result["id"]) + " insIt: " + str(insIt))

        if insIt:
            # @削除
            text = text.replace("@", "")
            # データセット
            ss = SearchList()
            ss.user_id = result["from_user"]
            ss.text = result["text"]
            ss.post_id = str(result["id"])
            ss.created_at = datetime.strptime(str(result["created_at"]),
                                              "%a, %d %b %Y %H:%M:%S +0000")
            # つぶやく(RT)
            msg = random.choice(Setting.res_words) + " RT " + from_user + " " + text
            if twitter.updateStatus(msg):
                ss.fin = True
                logging.info("success: " + result["text"])
            else:
                logging.info("failed: " + result["text"])
            ss.put()

def main():
  GetSearchList()

if __name__ == "__main__":
  main()
  
